import React, { useEffect, useState } from 'react'
import Panner from '../../../components/Panner';
import { Table, Pagination, Space, Button, Modal, Form, Input, Select, InputNumber, Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons'
import { goodsCategories, goodsDel, goodsEdit, goodsImgUpload, goodsList } from '../../../api/goods';
const { TextArea } = Input;

export default function List() {
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name'
    },
    {
      title: '商品分类',
      dataIndex: 'category'
    },
    {
      title: '商品价格',
      dataIndex: 'price'
    },
    {
      title: '商品图片',
      dataIndex: 'imgUrl'
    },
    {
      title: '商品描述',
      dataIndex: 'goodsDesc'
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='primary' style={{ fontSize: 13 }} onClick={() => showModal(record)}>编辑</Button>
          <Button type='primary' danger style={{ fontSize: 13 }} onClick={() => del(record)}>删除</Button>
        </Space>
      ),
    },
  ];
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState()
  const onPageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };
  // 当前行的数据
  const [good, setGood] = useState(
    {
      id: '',
      name: '',
      category: '',
      price: '',
      imgUrl: '',
      goodsDesc: ''
    }
  )
  // 获取商品列表
  const goods = async (value) => {
    const res = await goodsList(value)
    setTotal(res.data.total)
    let list = res.data.data
    setData(
      list.map(item => ({
        key: item.id,
        name: item.name,
        category: item.category,
        price: item.price,
        imgUrl: <img src={'http://8.137.157.16:9002' + item.imgUrl} alt="" style={{ width: 50, height: 50 }} />,
        goodsDesc: item.goodsDesc
      }))
    )
  }
  // 对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 点击修改，拿到当前行的数据显示在对话框中
  const showModal = (e) => {
    setIsModalOpen(true);
    // 获取商品详情
    const { key, name, category, price, imgUrl, goodsDesc } = e
    setGood({
      ...good,
      id: key,
      name: name,
      category: category,
      price: price,
      imgUrl: imgUrl.props.src.replace('http://8.137.157.16:9002/upload/imgs/goods_img/', ''),
      goodsDesc: goodsDesc
    })
  };
  // 确定后修改账号信息
  const handleOk = () => {
    edit(good)
    setIsModalOpen(false);
  };
  // 取消
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 分类设置
  const onGenderChange = (e) => {
    setGood({
      ...good,
      category: e
    })
  }
  const [componentSize, setComponentSize] = useState('default');
  const onFormLayoutChange = ({ size }) => {
    setComponentSize(size);
  };
  // 全部分类
  const [type, setType] = useState([])
  const allType = async (value) => {
    const res = await goodsCategories(value)
    const totalType = res.data.categories.map(item => {
      return item.cateName
    })
    setType(totalType)
  }
  // 商品图片 文件上传
  const uploadGoodsImg = async (e) => {
    const formData = new FormData()
    formData.append('file', e.file)
    const res = await goodsImgUpload(formData);
    setGood({
      ...good,
      imgUrl: res.data.imgUrl.replace('/upload/imgs/goods_img/', '')
    })
  }
  // 修改商品
  const edit = async (data) => {
    const res = await goodsEdit(data)
    const { code, msg } = res.data
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg,
      })
    } else {
      message.open({
        type: 'error',
        content: msg,
      })
    }
    goods({ currentPage, pageSize })
  }
  // 删除商品
  const del = async (value) => {
    const id = value.key
    const res = await goodsDel({ id })
    const { code, msg } = res.data
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg,
      })
    } else {
      message.open({
        type: 'error',
        content: msg,
      })
    }
    goods({ currentPage, pageSize })
  }



  useEffect(() => {
    goods({ currentPage, pageSize })
    allType()
  }, [currentPage, pageSize])
  return (
    <>
      <Panner>
        <div slot='title'>商品列表</div>
        <Table
          columns={columns}
          expandable={{
            expandedRowRender: (value) => (
              <>
                <span style={{ marginLeft: 50 }}>商品ID:{value.key}</span>
                <span style={{ marginLeft: '40%' }}>商品名:{value.name}</span>
              </>
            ),
          }}
          dataSource={data}
          pagination={false}
          style={{ marginBottom: 5 }}
        />
        <Modal title="修改账号信息"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}>
          <Form
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 14,
            }}
            layout="horizontal"
            initialValues={{
              size: componentSize,
            }}
            onValuesChange={onFormLayoutChange}
            size={componentSize}
            style={{
              maxWidth: 600,
            }}
          >
            <Form.Item label="商品名称">
              <Input onChange={(e) => setGood({ ...good, name: e.target.value })} value={good.name} />
            </Form.Item>
            <Form.Item label="商品分类">
              <Select onChange={onGenderChange} value={good.category}>
                {type.map((item, index) => {
                  return < Select.Option key={index} value={item}>{item}</Select.Option>
                })}
              </Select>
            </Form.Item>
            <Form.Item label="商品价格">
              <InputNumber min={1} defaultValue={1} onChange={(e) => setGood({ ...good, price: e })} value={good.price} />
            </Form.Item>
            <Form.Item label="商品图片" valuePropName="fileList">
              <Upload customRequest={uploadGoodsImg} listType="picture-card" showUploadList={false} maxCount={1}>
                <div style={{ position: 'relative', width: '102px', height: '102px' }}>
                  <button
                    style={{
                      border: 0,
                      background: 'none',
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: '100%',
                      height: '100%',
                    }}
                    type="button"
                  >
                    <PlusOutlined />
                  </button>
                  {good.imgUrl && <img src={'http://8.137.157.16:9002/upload/imgs/goods_img/' + good.imgUrl} style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', overflow: 'hidden' }} />}
                </div>
              </Upload>
            </Form.Item>
            <Form.Item label="商品描述">
              <TextArea rows={2} onChange={(e) => setGood({ ...good, goodsDesc: e.target.value })} value={good.goodsDesc} />
            </Form.Item>
          </Form>
        </Modal>
        <Pagination
          total={total}
          defaultPageSize={5}
          pageSizeOptions={[5, 10, 20, 30]}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={onPageChange}
          style={{ marginTop: 5 }}
        />
      </Panner>
    </>
  )
}
